<?php

class Platezh extends Controller {

	function index()
	{
		global $VALUTA;
		$time_from = strtotime("-1 week");
		$time_to = time();
		$filter = array(
			'user_id' => Auth::$user_id,
			'day_from' => date("j", $time_from),
			'month_from' => date("n", $time_from),
			'year_from' => date("Y", $time_from),
			'day_to' => date("j", $time_to),
			'month_to' => date("n", $time_to),
			'year_to' => date("Y", $time_to),
		);

		if(isset($_GET['valuta']))
		{
			$filter = $_GET;
			if(@!$filter['user_id'] || !$this->MUser->inMyStructure($filter['user_id']))
			{
				$filter['user_id'] = Auth::$user_id;
			}
			$user = $this->MUser->get($filter['user_id']);
			$allusers = array($user['id'] => $user);
			if(@$filter['include_children'])
			{
				$user['children'] = $this->MUser->getMyStructure($filter['user_id']);
				$user_structure = array($user['id'] => $user);
				$children_and_me = userGetArrayIndexByStructure($user_structure);
				$allusers = $children_and_me;
				$filter['user_id'] = array_keys($children_and_me);
			}
			$this->session->set_flashdata('fix_history_filter', $_SERVER['QUERY_STRING']);
		}
		else
		{
			$user = $this->MUser->get($filter['user_id']);
			$allusers = array($user['id'] => $user);
		}

		$me = $filter['user_id'] == Auth::$user_id ? $user : $this->MUser->get(Auth::$user_id);
		$me['children'] = $this->MUser->getMyStructure($me['id']);
		$structure = array();
		$structure[$me['id']] = $me;

		$schet_filters = array('user_id' => $filter['user_id']);
		if(@$filter['valuta'])
		{
			$schet_filters['valuta'] = $filter['valuta'];
		}
		$scheta = $this->MSchet->getList($schet_filters);

		$platezh_filters = array('sort' => 'from_date desc,id desc', 'add_fields' => array('can_delete'));
		if(count($scheta))
		{
			$platezh_filters['schet_id'] = array_keys($scheta);
		}
		else
		{
			$platezh_filters['id'] = -1;
		}
		if(@$filter['day_from'] && @$filter['month_from'] && @$filter['year_from'])
		{
			$platezh_filters['to_date>='] = dateToDb($filter['year_from']."-".$filter['month_from']."-".$filter['day_from'])." 00:00:00";
		}
		if(@$filter['day_to'] && @$filter['month_to'] && @$filter['year_to'])
		{
			$platezh_filters['from_date<='] = dateToDb($filter['year_to']."-".$filter['month_to']."-".$filter['day_to'])." 23:59:59";
		}
		$platezhi = $this->MPlatezh->getList($platezh_filters);
		$platezhi_info = array('plus' => array(), 'minus' => array(), 'komiss_plus' => array(), 'komiss_minus' => array());
		foreach($platezhi as $k => $p)
		{
			$koeff = isPlatezhBuy($p) ? -1 : 1;
			$p['itogo'] = $p['summ'] + $koeff * $p['komiss'];
			platezhFromTo($p);
			$platezhi[$k] = $p;

			$info_key = isPlatezhBuy($p) ? 'plus' : 'minus';
			if(!isset($platezhi_info[$info_key][$VALUTA[$p['valuta']]]))
			{
				$platezhi_info[$info_key][$VALUTA[$p['valuta']]] = 0;
				$platezhi_info['komiss_'.$info_key][$VALUTA[$p['valuta']]] = 0;
			}
			$platezhi_info[$info_key][$VALUTA[$p['valuta']]] += $p['summ'];
			$platezhi_info['komiss_'.$info_key][$VALUTA[$p['valuta']]] += $p['komiss'];
		}

		$this->load->model('MSetting');
		$setting = $this->MSetting->getMe();

		$this->load->view('head');
		$this->load->view('platezh/index', array('platezhi' => $platezhi, 'scheta' => $scheta, 'filter' => $filter, 'structure' => $structure, 'me' => $me, 'setting' => $setting, 'platezhi_info' => $platezhi_info));
		$this->load->view('foot');
	}

	function edit($id = 0)
	{
		$id = intval($id);
		$platezh = $this->MPlatezh->getFirstRow(array('id' => $id, 'add_fields' => array('can_delete')));
		if(!isMyPlatezh($platezh))
		{
			return;
		}
		if(!@$platezh['id'])
		{
			$platezh['from_date'] = date("Y-m-d");
			$platezh['to_date'] = date("Y-m-d");
			$platezh['can_delete'] = true;
		}
		if(!$platezh['can_delete'])
		{
			platezhFromTo($platezh);
		}
		$scheta = $this->MSchet->getList(array('user_id' => Auth::$user_id));
		$children_user = $this->MUser->getChildrenAndMe(Auth::$user_id);
		$this->load->model('MSetting');
		$setting = $this->MSetting->getMe();
		$this->load->view('head');
		$this->load->view('platezh/edit', array('platezh' => $platezh, 'scheta' => $scheta, 'children_user' => $children_user, 'setting' => $setting));
		$this->load->view('foot');
	}

	function save()
	{
		global $PLATEZH_TYPE, $ALLOWED_FILES;
		$id = intval($_POST['id']);
		$platezh = $this->MPlatezh->getFirstRow(array('id' => $id, 'add_fields' => array('can_delete')));
		if(!isMyPlatezh($platezh))
		{
			return;
		}
		$error = false;
		$save = array(
			'comment' => trim($_POST['comment'])
		);
		if(!@$platezh['id'] || $platezh['can_delete'])
		{
			$type = trim(@$_POST['type']);
			if(!isset($PLATEZH_TYPE[$type]))
			{
				return;
			}
			$save['type'] = $type;
			$save['summ'] = getFloat($_POST['summ']);
			$save['komiss'] = getFloat($_POST['komiss']);
			$save['from_date'] = dateToDb($_POST['year_from']."-".$_POST['month_from']."-".$_POST['day_from']);
			$save['to_date'] = dateToDb($_POST['year_to']."-".$_POST['month_to']."-".$_POST['day_to']);
			$schet_id = intval(@$_POST['schet_id']);
			if($schet_id)
			{
				$schet = $this->MSchet->get($schet_id);
				if(!@$schet['id'] || $schet['user_id'] != Auth::$user_id)
				{
					$error = true;
				}
				$save['schet_id'] = @$schet['id'];
				$save['valuta'] = $schet['valuta'];
			}
			if($type == 'buy')
			{
				$save['from_user_id'] = $_POST['from_user_id'];
				$save['to_user_id'] = Auth::$user_id;
			}
			if($type == 'sell' || $type == 'reklama')
			{
				$save['from_user_id'] = Auth::$user_id;
				$save['to_user_id'] = $_POST['to_user_id'];
			}
			if($type == 'komiss')
			{
				$save['from_user_id'] = Auth::$user_id;
				$save['to_date'] = $save['from_date'];
			}
			if($type == 'buy.drugoy' || $type == 'buy.des' || $type == 'buy.other')
			{
				$save['people'] = $_POST['from_people'];
				$save['to_user_id'] = Auth::$user_id;
			}
			if($type == 'sell.drugoy' || $type == 'sell.des' || $type == 'sell.other')
			{
				$save['from_user_id'] = Auth::$user_id;
				$save['people'] = $_POST['to_people'];
			}
		}
		for($i = 1; $i <= 5; $i++)
		{
			if(@$_FILES['file'.$i]['name'] && is_uploaded_file($_FILES['file'.$i]['tmp_name']))
			{
				$ex = strtolower(end(explode(".", $_FILES['file'.$i]['name'])));
				if(in_array($ex, $ALLOWED_FILES))
				{
					$filename = Auth::$user_id."_".md5(microtime()).".".$ex;
					if(move_uploaded_file($_FILES['file'.$i]['tmp_name'], UPLOAD_PATH.$filename))
					{
						$save['file'.$i] = $filename;
					}
				}
				else
				{
					$this->session->set_flashdata('system_error', 'Вы загрузили запрещённый тип файла: '.$_FILES['file'.$i]['name']);
					redirect('platezh');
					return;
				}
			}
			$save['file'.$i.'_comment'] = trim($_POST['file'.$i.'_comment']) == 'Комментарий' ? null : trim($_POST['file'.$i.'_comment']);
		}

		if($error)
		{
			$this->session->set_flashdata('system_error', 'Произошла внутреняя ошибка программы. Обратитесь к разработчикам');
			redirect('.');
		}
		for($i = 1; $i <= 5; $i++)
		{
			if(@$save['file'.$i])
			{
				@unlink(UPLOAD_PATH.$platezh['file'.$i]);
			}
		}
		$this->MPlatezh->save($save, $id);
		redirect('platezh');
	}

	function delete($id = 0)
	{
		$id = intval($id);
		$platezh = $this->MPlatezh->getFirstRow(array('id' => $id, 'add_fields' => array('can_delete')));
		if(!isMyPlatezh($platezh) || !$platezh['can_delete'])
		{
			return;
		}
		for($i = 1; $i <= 5; $i++)
		{
			if(@$platezh['file'.$i])
			{
				@unlink(UPLOAD_PATH.$platezh['file'.$i]);
			}
		}
		$this->MPlatezh->delete($id);
		redirect('platezh');
	}

	function info($platezh_id = null)
	{
		$platezh_id = intval($platezh_id);
		$platezh = $this->MPlatezh->get($platezh_id);
		if(!@$platezh['id'])
		{
			return;
		}
		$schet = $this->MSchet->get($platezh['schet_id']);
		if(!@$schet['id'])
		{
			return;
		}
		$me = $this->MUser->get(Auth::$user_id);
		$user = $this->MUser->getFirstRow(array('id' => $schet['user_id'], 'hi_like' => $me['hi']));
		if(!@$user['id'])
		{
			return;
		}
		
		$opers = $this->MOper->getList(array('platezh_id' => $platezh['id']));
		foreach($opers as $k => $o)
		{
			$opers[$k]['user'] = $this->MUser->get($o['user_id']);
		}
		$this->load->view('head', array('small' => true));
		$this->load->view('platezh/info', array('opers' => $opers));
		$this->load->view('foot');
	}





	
}

